execSync、 execFileSync 和 spawnSync 执行流程

execSync 、 execFileSync 和 spawnSync 的区别
execSync和execFileSync底层都是调用spawnSync。但是execSync和execFileSync在调用spawnSync之前的参数规范化逻辑不一样:execSync和exec都是调用normalizeExecArgs()execFileSync、spawn及spawnSync调用的是normalizeSpawnArguments()
spawnSync返回的是child_process.spawnSync(opts)中spawn_sync.spawn(options)(C++代码) 执行返回的结果resultexecSync和execFileSync都将spawnSync的执行结果做了同样的处理有错误,直接从主进程
threw错误在
execFileSync('ls -la')找不到文件时result.error
错误日志
child_process.js:642 throw err; ^ Error: spawnSync ls -la ENOENT at Object.spawnSync (internal/child_process.js:1041:20) at spawnSync (child_process.js:607:24) at Object.execFileSync (child_process.js:634:15) at Object.<anonymous> (/Users/jolly/Desktop/imooc/child_process/index.js:7:19) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 { errno: 'ENOENT', code: 'ENOENT', syscall: 'spawnSync ls -la', path: 'ls -la', spawnargs: [], error: [Circular], status: null, signal: null, output: null, pid: 6262, stdout: null, stderr: null }result.stdout和result.stderr中是null
在命令本身错误时:
lss -laresult.error = undefinedresult.stdout中的ArrayBuffer为空result.stderr中ArrayBuffer有值。result.stderr中的信息,将通过process.stderr.write(ret.stderr)打印在主进程的日志中:/bin/sh: lss: command not foundresult.status !== 0,打印result.stderr之后,threw 错误信息
没有错误,返回执行成功的结果输出流
stdout
使用示例
const cp = require('child_process');
const path = require('path');
execSyncconst stdout = cp.execSync('lss -la'); console.log('stdout: ', stdout.toString()); // 有异常不会执行execFileSyncconst stdout = cp.execFileSync(path.resolve(__dirname, 'test.shell')); console.log('stdout: ', stdout.toString()); // 有异常不会执行spawnSyncconst result = cp.spawnSync(path.resolve(__dirname, 'test.shell')); if (result.status === 0) { // 没有异常 console.log(result.stdout.toString()) } else { console.log(result) }